//
//  WeatherService.swift
//  WeatherTools
//
//  Created by 刘飞龙 on 2020/8/30.
//  Copyright © 2020 finals. All rights reserved.
//

import Foundation
class WeatherService: NSObject{
    
    static let HOST_WEATHER:NSString = "http://www.weather.com.cn/data/cityinfo/%@.html"
    
    func getWeather(cityCode:NSString,callback:WeatherCallback){
        return getData(url:WeatherService.HOST_WEATHER,cityCode:cityCode,callback:callback)
    }
    
    func getData(url:NSString,cityCode:NSString,callback: WeatherCallback){
        //构建网络请求连接
        let weatherUrl = NSString.init(format:url,cityCode)
        //构建URL
        let requestUrl:NSURL = NSURL(string:weatherUrl as String)!
        //构建请求
        let request = URLRequest(url: requestUrl as URL, cachePolicy:.useProtocolCachePolicy,timeoutInterval: 200)
        //构建HTTP SESSION
        let session = URLSession.shared
        //请求
        let dataTask = session.dataTask(with: request){
            (data,response,error) in
            if(error != nil){
                print(error as Any)
                if callback != nil {
                    callback.onFailed(error: "网络错误")
                }
                return
            }
            if response == nil {
                if callback != nil {
                    callback.onFailed(error: "网络无响应错误")
                }
                return
            }
            if data == nil {
                if callback != nil {
                    callback.onFailed(error: "数据为空")
                }
                return
            }
            //Json解析
            let str = String(data: data!, encoding: .utf8)
            let decoder = JSONDecoder();
            let resut = try! decoder.decode([String:WeatherInfo].self, from:data! as Data)
            let weatherInfo =  resut.values.first
            //如果回调不为空
            let callbackString = weatherInfo!.city + " " + weatherInfo!.weather + " " + weatherInfo!.temp1+"-" + weatherInfo!.temp2;
            let picString = String("http://www.weather.com.cn/m/i/weatherpic/29x20/" + weatherInfo!.img1)
            let pic = NSURL(string: picString)
            DispatchQueue.main.async {
                if callback != nil{
                    callback.onSuccess(weather: callbackString, url: pic! as URL)
                }
            }
        }
        dataTask.resume()
    }
}

protocol WeatherCallback {
    
    func onSuccess(weather:String,url:URL) -> ()
    
    func onFailed(error:String) -> ()
}
